<?php


namespace app\middleware;


use app\Request;
use think\facade\Config;
use app\services\JWTService;
use app\exceptions\AuthException;
use app\exceptions\ApiErrorCode;
/**
 * 后台登陆验证中间件
 * Class AdminAuthTokenMiddleware
 * @package app\adminapi\middleware
 */
class AdminAuthTokenMiddleware
{
    public function handle(Request $request, \Closure $next)
    {
        $authInfo = null;
        $token = trim(ltrim($request->header(Config::get('cookie.token_name', 'Authori-zation')), 'Bearer'));

        /** @var JWTService $service */
        $service = app()->make(JWTService::class);
        $res = $service->decode($token);
        
        if($res['code']){
            $request->userInfo = $res['data'];
        }else{
            throw new AuthException(ApiErrorCode::ERR_LOGIN);
        }   
       
        return $next($request);
    }
}
